import React, { Component } from "react";
import PropTypes from "prop-types";
import { Form, Input, Button, message, Divider } from "antd";
import './index.less';
const layout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 22 },
};
const tailLayout = {
  wrapperCol: { offset: 2, span: 22 },
};
export default class Login extends Component {
  loginReq = (v) => {
    this.post("/admin/login", {
      account: v.account,
      password: v.password,
    })
      .then((res) => {
        if (res.code === 200) {
          this.props.setLoginInfo(res.data);
          localStorage.setItem('my-login-token', res.data.token);
          message.success("登录成功", 1.5, () => {
            this.props.history.push({
              pathname: "/home",
            });
          });
        } else {
          message.error(res.msg || '登录失败')
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };

  onFinish = (values) => {
    this.loginReq(values)
  };

  onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  componentWillUnmount() {
    this.setState = () => false;
  }
  render() {
    return (
      <div className="login-container">
        <div className="mid">
          <div className="mid-title"><h2>管理员登录</h2></div>
          <Divider />
          <Form
            {...layout}
            name="basic"
            initialValues={{ remember: true }}
            onFinish={this.onFinish}
            onFinishFailed={this.onFinishFailed}
          >
            <Form.Item
              label="账号"
              name="account"
              rules={[{ required: true, message: "请输入账号" }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="密码"
              name="password"
              rules={[{ required: true, message: "请输入密码" }]}
            >
              <Input.Password />
            </Form.Item>

            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    );
  }
}

Login.contextTypes = {
  store: PropTypes.object,
};
